package com.ultimatech.wxservice.combusiness.service.impl;

import com.google.gson.Gson;
import com.ultimatech.webappdemo.base.BaseService;
import com.ultimatech.webappdemo.base.model.GongzhongHao;
import com.ultimatech.wxservice.combusiness.HttpClientUtil;
import com.ultimatech.wxservice.combusiness.dao.IComBusinesDao;
import com.ultimatech.wxservice.combusiness.service.IWxApi;
import com.ultimatech.wxservice.combusiness.vo.AccessTokenVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zhangleping on 2017/6/16.
 */
@Service("wxApi")
public class WxApiImpl extends BaseService implements IWxApi {

    private Logger logger = LoggerFactory.getLogger(WxApiImpl.class);

    @Value("${wxapi.accessToken.url}")
    private String accessTokenUrl;

    public String getAccessTokenUrl() {
        return accessTokenUrl;
    }

    public void setAccessTokenUrl(String accessTokenUrl) {
        this.accessTokenUrl = accessTokenUrl;
    }

    @Autowired
    private IComBusinesDao dao;

    public IComBusinesDao getDao() {
        return dao;
    }

    public void setDao(IComBusinesDao dao) {
        this.dao = dao;
    }

    @Override
    public void refreshAllAccessTokens() {
        List<GongzhongHao> gongzhongHaoList = this.getDao().getAllGongzhongHao();
        for (GongzhongHao gongzhongHao : gongzhongHaoList) {
            String url = MessageFormat.format(this.getAccessTokenUrl(), gongzhongHao.getAppid(), gongzhongHao.getAppsecret());
            String strJson = HttpClientUtil.httpGetRequest(url);
            Gson gson = this.getGsonBuilder().create();
            AccessTokenVo accessTokenVo = gson.fromJson(strJson, AccessTokenVo.class);
            if (accessTokenVo != null && accessTokenVo.getErrcode() == null && accessTokenVo.getErrmsg() == null) {
                gongzhongHao.setAccessToken(accessTokenVo.getAccessToken());
                gongzhongHao.setAtExpired(new Date(System.currentTimeMillis() + accessTokenVo.getExpiresIn()));
                this.getDao().saveGongzhongHao(gongzhongHao);
            } else {
                logger.error("获取微信接口access_token错误\n" + strJson);
            }
        }
    }
}
